package com.gingko.duominuo.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.gingko.duominuo.R
import com.gingko.duominuo.data.request.Count
import com.gingko.duominuo.databinding.FragmentTaskReviewInfoBinding
import com.gingko.duominuo.utils.singleClick
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class TaskReviewInfoCountFragment : BottomSheetDialogFragment() {
    private val mViewBinding: FragmentTaskReviewInfoBinding by lazy { FragmentTaskReviewInfoBinding.inflate(layoutInflater) }
    var callback: Callback? = null
    private var count: Count? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.CustomBottomSheetDialogTheme)
        count = arguments?.getParcelable(ARG_COUNT)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return mViewBinding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        count?.let {
            mViewBinding.etPlayNumber.setText(getRealCount(it.click_count))
            mViewBinding.etPlayNumber.selectAll()
            mViewBinding.etCollectNumber.setText(getRealCount(it.collect_count))
            mViewBinding.etCommentNumber.setText(getRealCount(it.comment_count))
            mViewBinding.etForwardNumber.setText(getRealCount(it.share_count))
            mViewBinding.etPraiseNumber.setText(getRealCount(it.digg_count))
        }
        mViewBinding.tvCancel.singleClick {
            dismissAllowingStateLoss()
        }
        mViewBinding.tvConfitm.singleClick {
            val playNum = mViewBinding.etPlayNumber.text?.toString()?.toIntOrNull()
            val collectNum = mViewBinding.etCollectNumber.text?.toString()?.toIntOrNull() ?: -1
            val commentNum = mViewBinding.etCommentNumber.text?.toString()?.toIntOrNull() ?: -1
            val forwardNum = mViewBinding.etForwardNumber.text?.toString()?.toIntOrNull() ?: -1
            val praiseNum = mViewBinding.etPraiseNumber.text?.toString()?.toIntOrNull() ?: -1
            callback?.onConfirm(Count(playNum, collectNum, commentNum, praiseNum, forwardNum))
            dismissAllowingStateLoss()
        }
    }

    private fun getRealCount(count: Int?): String {
        return if (count == null || count == -1) {
            ""
        } else {
            count.toString()
        }
    }

    companion object {
        private const val ARG_COUNT = "count"

        @JvmStatic
        fun newInstance(count: Count?) = TaskReviewInfoCountFragment().apply {
            arguments = Bundle().apply {
                putParcelable(ARG_COUNT, count)
            }
        }
    }

    interface Callback {
        fun onConfirm(count: Count)
    }
}